#include "../source/tcp_server.h"
#include "../source/byte_array.h"

class EchoServer: public framework::TcpServer
{
public:
    EchoServer(int type = 1):m_type(type) {}

    //客户端连接成功的回调函数  处理新连接的Socket类
    void handleClient(framework::Socket::ptr client) override; 

private:
    int m_type; //输出类型（2:二进制类型  1:文本类型）
};

void EchoServer::handleClient(framework::Socket::ptr client)
{
    std::cout << "handleClient " << *client << std::endl;
    framework::ByteArray::ptr ba(new framework::ByteArray);
    while(true)
    {
        ba->clear();
        std::vector<iovec> iovs;
        ba->getWriteBuffers(iovs, 1024);

        int rt = client->recv(&iovs[0], iovs.size());
        if(rt == 0)
        {
            std::cout << "client close: " << *client << std::endl;
            break;
        }
        else if(rt < 0)
        {
            std::cout << "client error rt=" << rt << " errno=" 
                << errno << " errstr=" << strerror(errno) << std::endl;
            break;
        }
        // std::cout << "rt = " << rt << std::endl;
        // std::cout << "data = " << std::string((char*)iovs[0].iov_base, rt);
        ba->setPosition(ba->getPosition() + rt);
        ba->setPosition(0);
        if(m_type == 1)
        {
            std::cout << ba->toString();
        }
        else
        {
            std::cout << ba->toHexString();
        }
        std::cout.flush();
    }

}

int type = 1;
void run()
{
    std::cout << "server type = " << type << std::endl;
    EchoServer::ptr es(new EchoServer(type));

    auto addr = framework::Address::LookupAny("0.0.0.0:6666");
    while(!es->bind(addr))
    {
        sleep(2);
    }
    es->start();
}

int main(int argc, char** argv)
{
    if(argc < 2)
    {
        std::cout << "used as[" << argv[0] << " -t] or [" << argv[0] << " -b]" << std::endl;
        return 0;
    }

    if(!strcmp(argv[1], "-b"))
    {
        type = 2;
    }

    framework::IOManager iom(2);
    iom.schedule(run);

    return 0;
}